<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Http\Logics\DingDing;
use App\Http\Logics\UtilLogic;
use App\Model\Admin;
use App\Model\DingDing as DingDingModel;
use App\Model\StudentClass;
use App\Model\StudentQuestion;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

/**
 * 学生问题吐槽反馈
 */
class StudentQuestionController extends Controller
{

    /**
     * 问题列表
     *
     * @param Request $request
     * @return void
     */
    public function index(Request $request)
    {
        $class_type = $request->class_type;
        $page_size = $request->page_size ?? 10;
        $query = StudentQuestion::orderBy('sf_student_question.status', 'asc')
            ->orderBy('sf_student_question.id', 'desc')
            ->select('sf_student_question.id', 'sf_student_question.status', 'sf_student_question.verify', 'sf_student_question.class_type', 'sf_student_question.class_name', 'sf_student_question.content', 'sf_student_question.created_time');
        if ($class_type) {
            $query->where('sf_student_question.class_type', $class_type);
        }

        return resJson(self::HTTP_0_SUCCESS, $query->paginate($page_size));
    }

    /**
     * 提交问题吐槽
     *
     * @param Request $request
     * @return json
     */
    public function feedback(Request $request)
    {
        $inputs = $request->all();
        $class = StudentClass::find($inputs['class_id']);
        if (!$class) {
            return resJson(self::HTTP_500_ERROR, '选择的班级不存在');
        }
        $teacher_ids = $inputs['teacher_ids'] ?? [];

        $feedback = [
            'status' => StudentQuestion::STATUS_NOT_READ,
            'verify' => StudentQuestion::VERIFY_PASS,
            'fingerprint' => $inputs['factor'] ?? '',
            'class_id' => $inputs['class_id'],
            'class_type' => $class->class_type,
            'class_name' => $class->class_name,
            'content' => $inputs['content'],
            'teacher_ids' => $teacher_ids,
            'created_time' => millisecond(),
        ];
        $question = StudentQuestion::create($feedback);

        // 目前只需要一个推送，按照UI类型来设定
        $config = DingDingModel::where('type', DingDingModel::TYPE_UI)->where('status', DingDingModel::STATUS_OPEN)->first();
        if ($config) {
            $push = new DingDing(
                $config->url,
                $config->secret
            );
            $title = '问题反馈';
            $classType = $class->class_type === StudentClass::TYPE_UI ? 'UI' : '前端';
            $className = $class->class_name;
            // $content = mb_substr($inputs['content'], 0, 50); // 50个字之内的显示完全
            $content = $inputs['content'] ?? '';
            $detailUrl = '';
            if ($config['click_url']) {
                $detailUrl = "{$config['click_url']}?id={$question->id}"; // 点击跳转到问题列表页
            }
            $at = '';
            if (!empty($teacher_ids)) {
                // 添加老师的话就@老师
                $teachers = Admin::whereIn('id', $teacher_ids)->select('nickname', 'phone')->get();
                $at = $teachers->reduce(function ($str, $item) {
                    return $str . '@' . $item->nickname;
                }, '');
            }
            $date = date('Y-m-d H:i:s');
            $text = <<<markdown
## {$title}
#### {$classType} {$className}
>{$content}{$at}
​
#### [详细链接]({$detailUrl})
#### {$date}
markdown;
            $res = $push->markdown($title, $text);
            Log::info(json_encode($res, JSON_UNESCAPED_UNICODE));
        }
        return resJson(self::HTTP_0_SUCCESS);
    }

    /**
     * 全部已读
     *
     * @return json
     */
    public function readAll()
    {
        StudentQuestion::where('status', StudentQuestion::STATUS_NOT_READ)->update(['status' => StudentQuestion::STATUS_READ]);
        return resJson(self::HTTP_0_SUCCESS);
    }

    /**
     * 状态更改为已读
     *
     * @param Request $request
     * @return json
     */
    public function read($id)
    {
        $studentQuestion = StudentQuestion::find($id);
        if ($studentQuestion) {
            $studentQuestion->status = StudentQuestion::STATUS_READ;
            $studentQuestion->save();
        }
        return resJson(self::HTTP_0_SUCCESS);
    }

    /**
     * 问题删除
     *
     * @param Request $request
     * @return json
     */
    public function destroy($id)
    {
        StudentQuestion::destroy($id);
        return resJson(self::HTTP_0_SUCCESS);
    }

    public function getClassAndTeacher()
    {
        $res = UtilLogic::getClassAndTeacher();
        return resJson(self::HTTP_0_SUCCESS, $res);
    }
}
